﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Xml;
using System.IO;
using System.Reflection;

namespace Scan
{
    public class ConfigurationKeys
    {
        /// <summary>
        /// 提供WebService地址
        /// </summary>
        public const string ServiceUrl = "dataSrvUrl";

        /// <summary>
        /// 管理员密码
        /// </summary>
        public const string AdminPassword = "adminPassword";

        /// <summary>
        /// PDA编号
        /// </summary>
        public const string PdaID = "pdaID";

        /// <summary>
        /// 退出时间日期
        /// </summary>
        public const string ExitDateTime = "exitDateTime";

        /// <summary>
        /// 连接方式(0:连线方式;1:离线方式)
        /// </summary>
        public const string OnLineType = "OnLineType";
    }

    class Configuration
    {
        public static NLog.Logger logger = NLog.LogManager.GetLogger("Configuration");

        Hashtable list = new Hashtable();

        private Configuration()
        {
            filePath = GetFilePath();
            CheckUtil.SetFileAttribute(filePath);

            Load();
        }

        private string GetFilePath()
        {
            return Assembly.GetExecutingAssembly().GetName().CodeBase + ".config";
        }

        private static readonly Configuration instance = new Configuration();
        public static Configuration Instance
        {
            get { return instance; }
        }

        private bool autoSave = false;
        public bool AutoSave
        {
            get { return autoSave; }
            set { autoSave = value; }
        }

        string filePath;
        public string FilePath
        {
            get { return filePath; }
            set { filePath = value; }
        }

        public OnLineType OnLineType
        {
            get
            {
                int temType = Configuration.Instance.GetInt(ConfigurationKeys.OnLineType);
                return (OnLineType)temType;
            }
            set 
            { 
                Configuration.Instance.SetValue(ConfigurationKeys.OnLineType, value);
            }
        }

        public void SetValue(string key, object value)
        {
            // update internal list
            list[key] = value;

            // update settings file
            if (autoSave)
            {
                Save();
            }
        }

        /// <summary>
        /// Return specified settings as string.
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetString(string key)
        {
            object result = null;
            lock (list.SyncRoot)
            {
                result = list[key];
            }
            return (result == null) ? String.Empty : result.ToString();
        }

        public DateTime GetDateTime(string key)
        {
            object result = null;
            lock (list.SyncRoot)
            {
                result = list[key];
            }
            return (result == null) ? DateTime.Now : Convert.ToDateTime(result);
        }

        /// <summary>
        /// Return specified settings as integer.
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public int GetInt(string key)
        {
            string result = GetString(key);
            return (result == String.Empty) ? 0 : Convert.ToInt32(result);
        }

        /// <summary>
        /// Return specified settings as boolean.
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool GetBool(string key)
        {
            string result = GetString(key);
            return (result == String.Empty) ? false : Convert.ToBoolean(result);
        }

        public void Load()
        {
            XmlTextReader reader = null;
            try
            {
                list.Clear();

                reader = new XmlTextReader(filePath);
                while (reader.Read())
                {
                    if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "add"))
                        list[reader.GetAttribute("key")] = reader.GetAttribute("value");
                }
            }
            catch (Exception ex)
            {
                logger.ErrorException("Load()", ex);
            }
            finally
            {
                if (reader.ReadState != ReadState.Closed)
                {
                    reader.Close();
                }
            }
        }

        public void Save()
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(filePath);

                XmlNodeList nodeList = doc.SelectNodes("/configuration/appSettings/add");
                foreach (XmlNode node in nodeList)
                {
                    node.Attributes["value"].Value = GetString(node.Attributes["key"].Value);
                }

                doc.Save(filePath);

            }
            catch (Exception ex)
            {
                logger.ErrorException("save()", ex);
            }
        }
    }
}
